import { useEffect, useRef } from "react";
import { ScrollView, Text, View } from "@tarojs/components";
import { useMap, useReactive } from "ahooks";

import Sticky from "@/components/app/Sticky";
import ByRadio from "@/components/ui/ByRadio";
import ByButton from "@/components/ui/ByButton";
import ListView from "@/components/app/ListView";
import BySearchBar from "@/components/ui/BySearchBar";
import ByPopupBottom from "@/components/ui/ByPopupBottom";

import useList from "@/hooks/useList";
import ApiWork from "@/api/work";

import { DispatchWorker } from "@/types/dispatch";
import { Worker, WorkflowWorkType } from "@/types/work";
import type { ByPopupBottomEvent } from "@/components/ui/ByPopupBottom";

const WorkerItem = ({
  source,
  checked,
  onChange,
}: {
  source: Worker;
  checked: boolean;
  onChange: (checked: boolean) => void;
}) => {
  return (
    <View
      className={`flex items-center rounded-xl p-4 mb-3 ${
        checked ? "bg-[var(--color-primary-light)]" : "bg-white shadow-black-1"
      }`}
      onClick={() => onChange(!checked)}
    >
      <ByRadio
        checked={checked}
        checkedColor="var(--color-primary)"
        uncheckedColor="#999"
      />

      <View className="flex-auto ml-3">
        <View className="flex justify-between">
          <Text>{source.workerName}</Text>
          {source.onBuildNum > 0 && (
            <Text className="text-sm text-primary">
              {source.onBuildNum}个在建工程
            </Text>
          )}
        </View>
        <View className="mt-3 text-xs text-third">{source.telPhone}</View>
      </View>
    </View>
  );
};

type PopupAddWorkerProps = {
  defaultWorkerType: string;
  selectedWorker: DispatchWorker[];

  // workTypeList: WorkflowWorkType[];
  // checked?: boolean;

  onConfirm: (worker: any[]) => void;
};

function transListToMap(list: DispatchWorker[]) {
  return list.reduce((map, item) => {
    map.set(item.workerId, item);
    return map;
  }, new Map());
}

export default ({
  // workTypeList,
  selectedWorker,
  defaultWorkerType,

  onCancel,
  onConfirm,
}: PopupAddWorkerProps & ByPopupBottomEvent) => {
  const ref = useRef(true);
  const [selectedMap, { get, set, remove }] = useMap(
    ref.current ? transListToMap(selectedWorker) : undefined
  );
  ref.current = false;

  const search = useReactive({
    workerName: "",
    workerType: defaultWorkerType,
  });

  const { loading, list, nextPage, resetToFirst } = useList<Worker>(
    ApiWork.workerList,
    { manual: true, defaultParams: [search] }
  );

  useEffect(() => {
    resetToFirst(search);
  }, [search.workerType, search.workerName]);

  const handleChange = (checked: boolean, worker: Worker) => {
    if (checked) {
      set(worker.workerId, worker);
    } else {
      remove(worker.workerId);
    }
  };

  return (
    <ByPopupBottom
      title="添加工人"
      slotFooter={
        <View className="text-center py-3">
          <ByButton
            className="w-2/3"
            size="large"
            onClick={() => onConfirm([...selectedMap.values()])}
          >
            确定
          </ByButton>
        </View>
      }
      onCancel={onCancel}
    >
      <View className="flex relative h-[70vh]">
        {/* <View className="flex-none left-0 h-full w-[200px] bg-[#f6f8fd] overflow-auto">
          {workTypeList.map((item) => (
            <View
              className={`h-[120px] flex-center ${
                item.name === search.workerType && "bg-[#23252a] text-white"
              }`}
              onClick={() => (search.workerType = item.name)}
            >
              {item.name}
            </View>
          ))}
        </View> */}

        <ScrollView
          scrollY
          className="flex-auto h-full"
          onScrollToLower={nextPage}
        >
          <View className="px-3">
            <Sticky position="top" className="mb-3 z-20">
              <BySearchBar
                onConfirm={(e) => (search.workerName = e)}
                onClear={() => (search.workerName = "")}
              />
            </Sticky>

            <ListView loading={loading} isEmpty={list.length == 0}>
              {list?.map((item) => (
                <WorkerItem
                  key={item.workerId}
                  source={item}
                  checked={!!get(item.workerId)}
                  onChange={(flag) => handleChange(flag, item)}
                />
              ))}
            </ListView>
          </View>
        </ScrollView>
      </View>
    </ByPopupBottom>
  );
};
